package com.baihan.angus.app.game.busshow.pop_dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.baihan.angus.app.game.basic.utils.AppUtil;
import com.baihan.angus.app.game.basic.utils.Loog;
import com.baihan.angus.app.game.basic.utils.Tooast;
import com.baihan.angus.app.game.basic.utils.net.NetConstant;
import com.baihan.angus.app.game.busshow.R;
import com.baihan.angus.app.game.common.data_center.remote.api.DownloadServer;
import com.tencent.smtt.sdk.TbsReaderView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import static com.blankj.utilcode.util.Utils.runOnUiThread;

public class HandBookDialog extends Dialog {

    private Context mContext;
    private WindowManager.LayoutParams mLayoutParams;
    private LinearLayout llProgress;
    private ImageView ivClose;
    private FrameLayout flContent;
    private TextView tvProgress;
    private ProgressBar progressBar;

    private TbsReaderView tbsReaderView;
    private String fileName;
    private String linkUrl;

    public HandBookDialog(@NonNull Context context) {
        super(context, R.style.FullDialog);
        this.mContext = context;
        initContentView();
        init(context);
    }

    private void init(Context context) {
        this.mContext = context;
        Window dialogWindow = this.getWindow();
        mLayoutParams = dialogWindow.getAttributes();
        mLayoutParams.width = AppUtil.getScreenWidth(context);
        mLayoutParams.height = AppUtil.getScreenHeight(context);
        dialogWindow.setAttributes(mLayoutParams);
        dialogWindow.getDecorView().setPadding(0, 180, 0, 0);
        dialogWindow.getDecorView().setBackgroundResource(android.R.color.transparent);
        dialogWindow.setGravity(Gravity.BOTTOM);
    }

    private void initContentView() {
        View dialogView = LayoutInflater.from(this.getContext()).inflate(R.layout.dialog_hand_book, (ViewGroup) null);
        setContentView(dialogView);
        ivClose = dialogView.findViewById(R.id.ivClose);
        llProgress = dialogView.findViewById(R.id.llProgress);
        flContent = dialogView.findViewById(R.id.flContent);
        tvProgress = dialogView.findViewById(R.id.tvProgress);
        progressBar = dialogView.findViewById(R.id.progressBar);

        ivClose.setOnClickListener(view -> {
            cancel();
            //销毁界面的时候一定要加上，否则后面加载文件会发生异常。
            if (null != tbsReaderView) {
                tbsReaderView.onStop();
            }
        });
    }

    public void initUrl(String linkUrl) {

        TbsReaderView.ReaderCallback readerCallback = new TbsReaderView.ReaderCallback() {
            @Override
            public void onCallBackAction(Integer integer, Object o, Object o1) {

            }
        };

        tbsReaderView = new TbsReaderView(mContext, readerCallback);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        flContent.addView(tbsReaderView, params);

        fileName = TextUtils.isEmpty(linkUrl) ? "" : linkUrl.substring(linkUrl.lastIndexOf("/") + 1);
//        File downFile = new File(AppUtil.WORD_FILE_SAVE_PATH + fileName);
        File cacheFile = new File(AppUtil.WORD_FILE_SAVE_PATH + fileName);
        if (cacheFile.exists()) {
            llProgress.setVisibility(View.GONE);
            displayFile(cacheFile.getPath(), fileName);
        } else {
            String cachePath = AppUtil.WORD_FILE_SAVE_PATH + fileName;
            llProgress.setVisibility(View.VISIBLE);
            downDoc(linkUrl, cachePath);
        }
    }

    public void downDoc(String url, String path) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(NetConstant.BASE_HOST)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        retrofit.create(DownloadServer.class).download(url).subscribeOn(Schedulers.io())
                .observeOn(Schedulers.single())
                .map(new Function<ResponseBody, String>() {
                    @Override
                    public String apply(ResponseBody responseBody) {
                        try {
                            long total = responseBody.contentLength();//需要下载的总大小
                            long current = 0;
                            InputStream inputStream = responseBody.byteStream();
                            //文件名
//                            String path = AppUtil.APK_FILE_SAVE_PATH + fileName;
//                            String p = DocumentPreviewActivity.this.getCacheDir() + fileName;
                            File file = new File(path);
                            if (!file.exists()) {
                                file.createNewFile();
                            }
                            FileOutputStream fileOutputStream = new FileOutputStream(path);
                            byte[] bytes = new byte[1024];
                            int len = 0;
                            float percent = 0;
                            while ((len = inputStream.read(bytes)) != -1) {
                                fileOutputStream.write(bytes, 0, len);
                                fileOutputStream.flush();
                                current = current + len;
//                                Loog.d("MediaFragment", "已经下载=" + current + " 需要下载=" + total);
                                //考虑用progressBar
                                percent = (float) current / total * 100;
                                long finalCurrent = current;
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        float percent = (float) finalCurrent / total * 100;
                                        tvProgress.setText((int) percent + "%");
                                        progressBar.setProgress((int) percent);
                                    }
                                });
                            }
                            fileOutputStream.flush();
                            fileOutputStream.close();
                            inputStream.close();
                            return path;
                        } catch (Exception e) {
                            Writer result = new StringWriter();
                            PrintWriter printWriter = new PrintWriter(result);
                            e.printStackTrace(printWriter);
                            printWriter.close();
                            Loog.d("document", "result = " + result.toString());
                            e.printStackTrace();
                            return null;
                        }
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
//                .compose(this.<String>bindToLifecycle())
                .subscribe(new Observer<String>() {
                    Disposable disposable;

                    @Override
                    public void onSubscribe(Disposable d) {
                        disposable = d;
//                        Tooast.normalInfo(mContext.getString(R.string.isSaving));
                    }

                    @Override
                    public void onNext(String b) {
                        if (!TextUtils.isEmpty(b)) {
//                            Tooast.success(mContext.getString(R.string.alreadySaveTo).replace("#P", b));
                            llProgress.setVisibility(View.GONE);
                            File file = new File(b);
                            displayFile(file.getPath(), fileName);
                        } else {
                            Tooast.warning(mContext.getString(R.string.savefailed));
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Tooast.warning(mContext.getString(R.string.savefailed));
                        if (disposable != null && !disposable.isDisposed())
                            disposable.dispose();
                    }

                    @Override
                    public void onComplete() {
                        if (disposable != null && !disposable.isDisposed())
                            disposable.dispose();
                    }
                });
    }

    //加载文件
    private void displayFile(String filePath, String fileName) {
//        增加下面一句解决没有TbsReaderTemp文件夹存在导致加载文件失败
        String bsReaderTemp = Environment.getExternalStorageDirectory().getPath();
        File bsReaderTempFile = new File(bsReaderTemp);
        if (!bsReaderTempFile.exists()) {
            Log.d("print", "准备创建/TbsReaderTemp！！");
            boolean mkdir = bsReaderTempFile.mkdir();
            if (!mkdir) {
                Log.d("print", "创建/TbsReaderTemp失败！！！！！");
            }
        }
        Bundle bundle = new Bundle();
        bundle.putString("filePath", filePath);
        bundle.putString("tempPath", Environment.getExternalStorageDirectory().getPath());
        boolean result = tbsReaderView.preOpen(getFileType(fileName), false);
        if (result) {
            tbsReaderView.openFile(bundle);
        }
    }

    /***
     * 获取文件类型
     *
     * @param path 文件路径
     * @return 文件的格式
     */
    private String getFileType(String path) {
        String str = "";

        if (TextUtils.isEmpty(path)) {
            return str;
        }
        int i = path.lastIndexOf('.');
        if (i <= -1) {
            return str;
        }
        str = path.substring(i + 1);
        Loog.dTag("type", "type = " + str);
        return str;
    }


}
